package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class RedisTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 定时处理器
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天的凌晨1点
    public void deleteImg(){
        log.info("定期处理阿里云的垃圾图片");
        SetOperations setOperations = redisTemplate.opsForSet();
        Set<String> intersect = setOperations.intersect("AliOssUtilFirst", "imgFileLocal");//差集数据集合
        for (String s : intersect) {
            setOperations.add("intersect",s);//将差集存放到另一个redis表中；
        }

        //对比差集表中的数据与云端数据的差集，就是垃圾数据了
        Set<String> difference = setOperations.difference("AliOssUtilFirst", "intersect");
        //要删除的就是这个里面的数据，注：需要切割，因为redis的存储和阿里云格式不一样
        if (difference!=null && difference.size()>0){
            for (String file : difference) {
                String[] split = file.split("/");//每个图片路径的切割后集合
                aliOssUtil.delete(split[3]);//根据遍历到的路劲删除阿里云数据
                //同时还得需要清除掉redis中的多余数据
                setOperations.remove("AliOssUtilFirst",file);
            }
        }
        redisTemplate.delete("intersect");


    }
}
